// 生成publish文件之前，先删除
var fs = require('fs'); // 引入fs模块  
var path = require('path')

//复制单个文件
var copyFile = function(srcPath, tarPath, cb) {
  var rs = fs.createReadStream(srcPath);
  rs.on('error', function(err) {
    if (err) {
    console.log('read error', srcPath)
    }
    cb && cb(err)
  })

  var ws = fs.createWriteStream(tarPath)
  ws.on('error', function(err) {
    if (err) {
    console.log('write error', tarPath)
    }
    cb && cb(err)
  })
  ws.on('close', function(ex) {
    cb && cb(ex)
  })
  rs.pipe(ws)
}

//删除文件夹
function deleteall(path) { 
  var files = [];  
  if(fs.existsSync(path)) {  
      files = fs.readdirSync(path);  
      files.forEach(function(file, index) {  
          var curPath = path + "/" + file;  
          if(fs.statSync(curPath).isDirectory()) { // recurse  
              deleteall(curPath);  
          } else { // delete file  
              fs.unlinkSync(curPath);  
          }  
      });  
      fs.rmdirSync(path);  
  };
}; 

//检测文件夹存在，删了重新建
function createNewPublish(path) {
  // console.log('删除publish重新生成');
  deleteall(path);
  fs.mkdirSync(path);
}

//复制文件夹下所有文件
var copyFolder = function(srcDir, tarDir, cb) {
  createNewPublish(tarDir);

 fs.readdir(srcDir, function(err, files) {
  var count = 0
  var checkEnd = function() {
   ++count == files.length && cb && cb()
  }

  if (err) {
   checkEnd()
   return
  }

  files.forEach(function(file) {
   var srcPath = path.join(srcDir, file)
   var tarPath = path.join(tarDir, file)

   fs.stat(srcPath, function(err, stats) {
    if (stats.isDirectory()) {
     console.log('mkdir', tarPath)
     fs.mkdir(tarPath, function(err) {
      if (err) {
       console.log(err)
       return
      }
      copyFolder(srcPath, tarPath, checkEnd)
     })
    } else {
     copyFile(srcPath, tarPath, checkEnd)
    }
   })
  })

  //为空时直接回调
  files.length === 0 && cb && cb()
 })
}

//将app文件夹的文件拷贝到publish
copyFolder('app', 'publish', function(err) {
 if (err) {
   console.log("复制出错");
  return
}else{
  console.log("复制成功");
}

 //continue
})



